package com.hd.trans.ui.base

import android.Manifest
import android.os.Bundle
import android.view.View
import com.hd.trans.TranslationInterior
import com.hd.trans.framework.click.XClickUtil
import com.hd.trans.homefun.EventCode
import com.hd.trans.homefun.FreeTrialCount
import com.hd.trans.homefun.FreeTrialTime
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.utils.PermissionCallback
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.preference.Preferences

/**
 * 拦截处理
 * 权限申请处理
 */
abstract class LimitBaseActivity: BaseActivity(), View.OnClickListener {

    private var freeTrialTime: FreeTrialTime = FreeTrialTime()
    private var freeTrialCount: FreeTrialCount = FreeTrialCount()
    abstract val pageType: EventCode

    companion object {
        @JvmStatic
        var limitListener: LimitUseListener? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        checkPageType()
        getFreeTrialCount()
        getFreeTrialTime()
    }

    private fun checkPageType() {
        if (pageType.code <= 100 || pageType.code > 200){
            throw IllegalArgumentException("pageType.code must be in 101-200")
        }
    }

    fun isVip():Boolean{
        return limitListener?.isAllowTransit(pageType)?:true
    }

    private fun isHaveFreeTrial(eventCode: EventCode):Boolean {
        return when (eventCode) {
            EventCode.TEXT_TRANSLATE,
            EventCode.CAMERA_TRANS,
            EventCode.WEB_TRANS,
            EventCode.WORD_TRANS,
            EventCode.VOICE_FIRST_AID_KIT -> {
                freeTrialCount.isHaveFree()
            }
            EventCode.VOICE_TRANSLATE,
            EventCode.SIMUL_TRANSLATE -> {
                freeTrialTime.isHaveFree()
            }
            else -> {
                false
            }
        }
    }

    /**
     * 消耗免费试用次数
     */
    fun consumeFreeTrial(){
        if(isVip()){
            return
        }
        freeTrialCount = freeTrialCount.consumeFreeTrial()
        when (pageType) {
            EventCode.TEXT_TRANSLATE -> {
                Preferences.textTransFreeTimes = freeTrialCount
            }
            EventCode.CAMERA_TRANS -> {
                Preferences.pictureTransFreeTime = freeTrialCount
            }
            EventCode.VOICE_FIRST_AID_KIT -> {
                Preferences.firstAidKitFreeTime = freeTrialCount
            }
            EventCode.WEB_TRANS -> {
                Preferences.webTransFreeTime = freeTrialCount
            }
            EventCode.WORD_TRANS -> {
                Preferences.wordTransFreeTime = freeTrialCount
            }
            else -> {
                if (TranslationInterior.isDebug()){
                    throw IllegalArgumentException("pageType not support")
                }
            }
        }
        if(freeTrialCount.getFreeCount() <= 0){
            ToastUtils.showNormal("免费试用次数已用完")
        }else{
            ToastUtils.showNormal("剩余试用次数${freeTrialCount.getFreeCount()}" + "次")
        }
    }
    /**
     * 消耗免费试用时长
     */
    fun consumeFreeTrialTime(timeMillis: Long){
        consumeFreeTrialTime(timeMillis, true)
    }

    fun consumeFreeTrialTime(timeMillis: Long, showTime: Boolean){
        if(isVip()){
            return
        }
        freeTrialTime = freeTrialTime.consumeFreeTrial(timeMillis)
        when (pageType) {
            EventCode.VOICE_TRANSLATE -> {
                Preferences.voiceTransFreeTime = freeTrialTime
            }
            EventCode.SIMUL_TRANSLATE -> {
                Preferences.simulTransFreeTime = freeTrialTime
            }
            else -> {
                if (TranslationInterior.isDebug()){
                    throw IllegalArgumentException("pageType not support")
                }
            }
        }
        if (showTime) {
            if(freeTrialTime.getFreeTime() <= 0){
                ToastUtils.showNormal("免费试用时长已用完")
            }else{
                ToastUtils.showNormal("剩余试用时长${freeTrialTime.getFreeTime()}" + "秒")
            }
        }
    }

    /**
     * 拦截处理
     * @param canTrial 是否可以试用
     * @param title 标题
     * @param name 名称
     * @param tab 标签
     * @return 是否拦截
     */
    fun intercept(canTrial: Boolean = false): Boolean{
        return intercept(canTrial, null, null, null)
    }
    fun intercept(canTrial: Boolean = false, title: String? = null, name: String? = null, tab: String? = null): Boolean{
        if(isVip()){
            return false
        }
        if(canTrial && isHaveFreeTrial(pageType)){
            return false
        }
        //拦截成功，回调执行拦截处理
        limitListener?.intercept(pageType, title, name, tab)
        return true
    }

    fun intercept(eventCode: EventCode): Boolean{
        if(isVip()){
            return false
        }
        if(isHaveFreeTrial(eventCode)){
            return false
        }
        //拦截成功，回调执行拦截处理
        limitListener?.intercept(eventCode)
        return true
    }

    fun requestPermission(permissions: Array<String>, callback: PermissionCallback){
        val isIntercept = limitListener?.interceptPermission(this, pageType, permissions, callback)?:false
        if(!isIntercept){
            // app未拦截，sdk申请权限
            permissionUtil.checkIsHavePermission(this, permissions) {
                callback.doNext()
            }
        }
    }

    fun hasStoragePermission():Boolean{
        return permissionUtil.checkIsHavePermission(this, arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)
        )
    }

    fun hasAudioPermission():Boolean{
        return permissionUtil.checkIsHavePermission(this, arrayOf(
            Manifest.permission.RECORD_AUDIO)
        )
    }

    fun hasCameraPermission():Boolean{
        return permissionUtil.checkIsHavePermission(this, arrayOf(
            Manifest.permission.CAMERA)
        )
    }

    /**
     * 申请存储权限
     * @param callback 权限回调
     */
    fun requestStoragePermission(callback: PermissionCallback){
        val permissions = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)
        requestPermission(permissions, callback)
    }
    /**
     * 申请相机权限
     * @param callback 权限回调
     */
    fun requestCameraPermission(callback: PermissionCallback){
        val permissions = arrayOf(
            Manifest.permission.CAMERA)
        requestPermission(permissions, callback)
    }
    /**
     * 申请麦克风权限
     * @param callback 权限回调
     */
    fun requestAudioPermission(callback: PermissionCallback){
        val permissions = arrayOf(
            Manifest.permission.RECORD_AUDIO)
        requestPermission(permissions, callback)
    }
    /**
     * 请求悬浮窗权限
     */
    fun requestFloatWindowPermission(callback: PermissionCallback){
        val permissions = arrayOf(
            Manifest.permission.SYSTEM_ALERT_WINDOW)
        requestPermission(permissions, callback)
    }

    /**
     * 获取免费试用次数
     */
    private fun getFreeTrialCount(){
        val freeCount = limitListener?.getFreeTrialCount(pageType)?:0
        when(pageType){
            EventCode.TEXT_TRANSLATE ->{
                freeTrialCount = Preferences.textTransFreeTimes
                if(freeTrialCount.total != freeCount){//数值有变动，更新
                    freeTrialCount = FreeTrialCount(freeCount,0)
                    Preferences.textTransFreeTimes = freeTrialCount
                }
            }
            EventCode.CAMERA_TRANS ->{
                freeTrialCount = Preferences.pictureTransFreeTime
                if(freeTrialCount.total != freeCount){//数值有变动，更新
                    freeTrialCount = FreeTrialCount(freeCount,0)
                    Preferences.pictureTransFreeTime = freeTrialCount
                }
            }
            EventCode.VOICE_FIRST_AID_KIT ->{
                freeTrialCount = Preferences.firstAidKitFreeTime
                if(freeTrialCount.total != freeCount){//数值有变动，更新
                    freeTrialCount = FreeTrialCount(freeCount,0)
                    Preferences.firstAidKitFreeTime = freeTrialCount
                }
            }
            EventCode.WEB_TRANS ->{
                freeTrialCount = Preferences.webTransFreeTime
                if(freeTrialCount.total != freeCount){//数值有变动，更新
                    freeTrialCount = FreeTrialCount(freeCount,0)
                    Preferences.webTransFreeTime = freeTrialCount
                }
            }
            EventCode.WORD_TRANS ->{
                freeTrialCount = Preferences.wordTransFreeTime
                if(freeTrialCount.total != freeCount){//数值有变动，更新
                    freeTrialCount = FreeTrialCount(freeCount,0)
                    Preferences.wordTransFreeTime = freeTrialCount
                }
            }
        }

    }
    /**
     * 获取免费试用时长
     */
    private fun getFreeTrialTime(){
        val time = limitListener?.getFreeTrialTime(pageType)?:0L
        when(pageType){
            EventCode.VOICE_TRANSLATE ->{
                freeTrialTime = Preferences.voiceTransFreeTime
                if(freeTrialTime.total != time){
                    freeTrialTime = FreeTrialTime(time,0L)
                    Preferences.voiceTransFreeTime = freeTrialTime
                }
            }
            EventCode.SIMUL_TRANSLATE ->{
                freeTrialTime = Preferences.simulTransFreeTime
                if(freeTrialTime.total != time){
                    freeTrialTime = FreeTrialTime(time,0L)
                    Preferences.simulTransFreeTime = freeTrialTime
                }
            }
        }
    }

    /**
     * 快速点击
     */
    protected open fun onFastClick(v: View?){}

    /**
     * 不允许快速点击
     */
    protected open fun onViewClick(v: View?){}

    override fun onClick(v: View?) {
        onFastClick(v)
        if (XClickUtil.isFastDoubleClick(v, XClickUtil.INTERVAL_MILLIS.toLong())) {
            return
        }
        onViewClick(v)
    }
}